package tree.stream;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import tree.person.Person;
import com.thoughtworks.xstream.XStream;


/** class manage XStream */
public class XmlStream extends XStream {

	/** XML string file */
	private String xml;


	/** default constructor */
	public XmlStream() {
		super();
		this.xml = "";
	}


	/** method add one Person */
	public boolean addOne(Person person) {
		try {
			this.xml += super.toXML(person) + "\n";
			return true;
		}
		catch (Exception e) {
			System.err.println("Error: Add to xml string error.");
			return false;
		}

	}


	/** method add list of Persons */
	public boolean addList(List<Person> list) {
		
		for(int i = 0; list.size() > i; i++) {
			if (!this.addOne(list.get(i))) {
				return false;
			}
		}
		return true;
	}


	/** method load XML file */
	public boolean load(String fileName) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(fileName + ".xml"));
			String line = "";
			
		    while((line = br.readLine()) != null) {
		    	this.xml += line;
		    }
			return true;

		} catch (FileNotFoundException ex) {
			System.err.println("Error: xml file not found.");
			return false;
		} catch (IOException ex) {
			System.err.println("Error: xml file error.");
			return false;
		}
	}


	/** method save XML file */
	public boolean save(String fileName) {
		try {
			FileWriter fw = new FileWriter(fileName + ".xml");
			fw.write("<tree>\n" + this.xml + "</tree>");
			fw.flush();
			fw.close();
			return true;

		} catch (IOException ex) {
			System.err.println("Error: xml file save error.");
			return false;
		}
	}


	/** get XML string file */
	public String getXML() {
		return this.xml;
	}
}
